package com.heima.behavior.service.impl;

import com.heima.behavior.dto.FollowBehaviorDto;
import com.heima.behavior.entity.ApFollowBehavior;
import com.heima.behavior.service.IApFollowBehaviorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
public class ApFollowBehaviorServiceImpl implements IApFollowBehaviorService {
    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 用户行为记录
     * @param dto
     */
    @Override
    public void saveFollow(FollowBehaviorDto dto) {
        //构建app关注行为表
        ApFollowBehavior apFollowBehavior = new ApFollowBehavior();
        //填充数据
        BeanUtils.copyProperties(dto,apFollowBehavior);
        apFollowBehavior.setCreatedTime(new Date());
        //查看当前用户是否有关注过该作者
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(dto.getUserId()))
                .addCriteria(Criteria.where("followId").is(dto.getFollowId()));
        ApFollowBehavior one = mongoTemplate.findOne(query, ApFollowBehavior.class);
        if (one == null){
            //没有关注过
            mongoTemplate.save(apFollowBehavior);
        }else {
            if (dto.getOperation() != one.getOperation()){
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
            }
        }
    }
}
